import { useEffect, useMemo, useState } from 'react';
import SubPageContent from '../../components/SubPageContent';
import SubPageHeader from '../../components/SubPageHeader';
import PaginationTable from '../../components/PaginationTable';
import { AnnotationType, KnowMenu } from '@/types/know/know';
import knowService from '@/api/services/knowService';
import { Button, Drawer, Flex, Input, message, PaginationProps, Spin, TableProps } from 'antd';
import TestChatBox from '../govern/components/TestChatBox';
import { Message } from '@/types/chat';
import Markdown from '@/components/markdown';
import appService from '@/api/services/appService';
import PagesHeader from '@/components/pages-header';
import { SvgIcon } from '@/components/icon';
import Tables from '@/components/tables/tables';
import NotData from '@/components/NotData';
import { useDebounceFn } from 'ahooks';
import useModal from '@/hooks/use-modal/useModal';

const Approval = () => {
  const [selectedIndex, setSelectedIndex] = useState(0);
  const [searchText, setSearchText] = useState('');
  const [refreshKey, setRefreshKey] = useState(0);
  const [showTestDrawer, setTestDrawer] = useState(false);
  const [historyMessages, setHistoryMessages] = useState<Message[]>([]);
  const [currentItem, setCurrentItem] = useState<AnnotationType | undefined>(undefined);
  // table选中的数据id
  const [tableSelectEdRows, setTableSelectEdRows] = useState<React.Key[]>([]);
  // 定义分页相关状态
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [total, setTotal] = useState(0);
  const [datas, setDatas] = useState<any[]>([]);
  const [loading, setLoading] = useState(false);

  // 定义表格引用和表格大小
  const [scroll, setScroll] = useState({ x: 'calc(700px + 50%)', y: 'calc(80vh - 100px)' });
  const [selectedRows, setSelectedRows] = useState([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const modal = useModal('personnel', 'delete', 'edit');

  const queryParams = new URLSearchParams(location.search);
  const appId = queryParams.get('appId') || '';

  // 监听分页和搜索框变化，获取数据
  useEffect(() => {
    checkPage();
    run();
  }, [page, pageSize, total]);

  // 监听搜索框变化，重置分页，获取数据
  useEffect(() => {
    setPage(1);
    setPageSize(10);
    run();
  }, [searchText]);

  useEffect(() => {
    modal.personnel.open();
  }, []);

  const refersh = () => {
    setRefreshKey((prev) => prev + 1);
  };

  const publish = async (items: AnnotationType[]) => {
    try {
      await knowService.publishAnnotation({
        ids: items.map((item) => item.recordId),
      });
      message.success('发布成功');
      refersh();
      run();
    } catch (error) {
      console.error(error);
      message.error('发布失败');
    }
  };

  const reject = async (items: AnnotationType[]) => {
    try {
      await knowService.withdrawAnnotation({
        ids: items.map((item) => item.recordId),
      });
      message.success('打回成功');
      refersh();
      run();
    } catch (error) {
      console.error(error);
      message.error('打回失败');
    }
  };

  const testClicked = async (item: AnnotationType) => {
    const appResponse = await appService.appDetail(item.appId);
    setCurrentItem({ ...item, shareId: appResponse?.share_id });
    setTestDrawer(true);
  };

  const columns = [
    {
      title: '应用名称',
      dataIndex: 'appName',
      key: 'appName',
      width: 150,
    },
    {
      title: '问题',
      dataIndex: 'q',
      key: 'q',
      width: 150,
    },
    {
      title: '预期回答',
      dataIndex: 'a',
      key: 'a',
      render: (a: string) => {
        return <Markdown source={a} />;
      },
      width: 450,
    },
    {
      title: '入库',
      width: 100,
      dataIndex: 'datasetName',
      key: 'datasetName',
    },
    {
      title: '标注人',
      width: 120,
      dataIndex: 'userName',
      key: 'userName',
    },
    {
      title: '状态',
      width: 100,
      render: () => {
        return <span>待发布</span>;
      },
    },
    {
      title: '操作',
      width: 200,
      key: 'operation',
      render: (_, record: AnnotationType) => (
        <div className="flex gap-2">
          <Button
            size="small"
            type="text"
            onClick={() => {
              publish([record]);
            }}
          >
            <span className="flex items-center text-@brand-color">
              <SvgIcon icon="message-ic7" size="15" className="mr-1" />
              发布
            </span>
          </Button>
          <Button
            size="small"
            type="text"
            onClick={() => {
              reject([record]);
            }}
          >
            <span className="flex items-center text-@brand-color">
              {' '}
              <SvgIcon icon="message-ic8" size="15" className="mr-1" />
              打回
            </span>
          </Button>
          <Button size="small" type="text" onClick={() => testClicked(record)}>
            <span className="flex items-center text-@brand-color">
              {' '}
              <SvgIcon icon="message-ic9" size="15" className="mr-1" />
              测试效果
            </span>
          </Button>
        </div>
      ),
    },
  ];

  const selectOperators = [
    {
      name: '发布',
      onClick: async (items: any[]) => {
        publish(items);
      },
    },
    {
      name: '打回',
      onClick: async (items: any[]) => {
        reject(items);
      },
    },
  ];

  const menus: KnowMenu[] = useMemo(() => {
    return [
      {
        key: 0,
        title: '问答对审核',
        children: (
          <PaginationTable
            refreshKey={refreshKey}
            rowKey="recordId"
            columns={columns}
            searchText={searchText}
            api={knowService.getAnnotations}
            selectOperators={selectOperators}
          />
          // <div>未知问题</div>
        ),
      },
    ];
  }, [searchText, selectedIndex, refreshKey]);

  const checkPage = () => {
    const newTotalPages = Math.max(Math.ceil(total / pageSize), 1);
    if (page > newTotalPages) {
      setPage(newTotalPages);
    }
  };

  /**
   * @description: 表格多选
   * @return {*}
   */
  const rowSelection: TableProps['rowSelection'] = {
    onChange: (newSelectedRowKeys: React.Key[]) => {
      setTableSelectEdRows(newSelectedRowKeys);
    },
  };
  // 使用防抖函数，延迟获取数据
  const { run } = useDebounceFn(
    () => {
      getDatas();
    },
    {
      wait: 500,
    },
  );
  // 获取数据函数
  const getDatas = async () => {
    try {
      const res = await knowService.getAnnotations({
        page: page,
        page_size: pageSize,
        searchText: searchText,
        type: '',
        app_id: appId,
      });
      setDatas(res?.list || []);
      setTotal(res?.total || 0);
      modal.personnel.close();
    } catch (error) {
      console.error(error);
    } finally {
    }
  };
  const onChange: PaginationProps['onChange'] = (current, pageSize) => {
    setPage(current);
    setPageSize(pageSize);
  };

  return (
    <div className="flex h-full flex-col overflow-hidden">
      <PagesHeader>标注审批</PagesHeader>
      <div className=" flex flex-1 flex-col rounded-default bg-[#FFF] px-5">
        <div className=" flex items-center justify-between ">
          <Input
            placeholder="请输入内容"
            onChange={(e: any) => {
              //拿到搜索的数据
              setSearchText(e.target.value);
            }}
            value={searchText}
            suffix={<SvgIcon icon="work-ic6" size={16} />}
            className="mt-5 !rounded-md"
            style={{
              height: '32px',
              width: '240px',
            }}
          />
          <div className="flex h-4 items-center">
            <>
              <span className="text-[#1D2129]">
                已选择 <span className="font-semibold">{tableSelectEdRows.length}</span> 项
              </span>
              <div
                className="mx-4 flex h-[32px] w-[68px] cursor-pointer items-center justify-center rounded-md border border-[#1B6DFA] text-center  text-@brand-color"
                onClick={() => {
                  let rows: any = tableSelectEdRows.map((item) => {
                    return {
                      recordId: item,
                    };
                  });
                  if (tableSelectEdRows.length === 0) {
                    return;
                  }
                  publish(rows);
                  setTableSelectEdRows([]);
                }}
              >
                <SvgIcon icon="message-ic7" size="20" className="mr-1" />
                发布
              </div>
              <div
                className="flex h-[32px] w-[68px] cursor-pointer items-center justify-center rounded-md border border-[#1B6DFA] text-center  text-@brand-color"
                onClick={() => {
                  let rows: any = tableSelectEdRows.map((item) => {
                    return {
                      recordId: item,
                    };
                  });
                  if (tableSelectEdRows.length === 0) {
                    return;
                  }
                  reject(rows);
                  setTableSelectEdRows([]);
                }}
              >
                <SvgIcon icon="message-ic8" size="20" className="mr-1" />
                打回
              </div>
            </>
          </div>
        </div>
        {modal.personnel.isOpen ? (
          <Flex align="center" gap="middle" className="flex h-full items-center justify-center">
            <Spin size="large" />
          </Flex>
        ) : (
          <>
            {total > 0 ? (
              <div className="mt-4 flex h-full flex-1 flex-col justify-between rounded-[20px]   text-[#292D32]">
                <Tables
                  rowSelection={{
                    type: 'checkbox',
                    ...rowSelection,
                    selectedRowKeys: tableSelectEdRows,
                  }}
                  rowKey="recordId"
                  rowClassName="bg-[#F6F7FB]"
                  columns={columns}
                  dataSource={datas}
                  pagination={false}
                  // scroll={scroll}
                  paginationProps={{
                    total: total,
                    current: page,
                    pageSize: pageSize,
                    onChange: onChange,
                  }}
                />
              </div>
            ) : (
              <NotData />
            )}
          </>
        )}
      </div>

      {/* <SubPageHeader
        menus={menus}
        title=""
        isRootDisplay={false}
        selectedIndex={selectedIndex}
        onChangeIndex={(index) => setSelectedIndex(index)}
        onSearchTextChanged={(text) => setSearchText(text)}
      />
      <SubPageContent menus={menus} selectedIndex={selectedIndex} /> */}
      <Drawer
        className="know-gov-drawer"
        title="测试"
        placement="right"
        // width={'auto'}
        width={'50%'}
        onClose={() => {
          setTestDrawer(false);
          setHistoryMessages([]);
        }}
        open={showTestDrawer}
        destroyOnHidden={true}
      >
        <div className="h-full bg-[#edeff7] p-2">
          <TestChatBox
            open={showTestDrawer}
            initChatId={currentItem?.chatId!}
            initChatMessage={currentItem?.q!}
            initAppId={currentItem?.appId!}
            initShareId={currentItem?.shareId!}
          />
        </div>
      </Drawer>
    </div>
  );
};

export default Approval;
